package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.enums.StatusEnum;
import com.xxx.pojo.Email;
import com.xxx.pojo.Subscribe;
import com.xxx.service.SubscribeService;
import com.xxx.service.impl.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/subscribe")
public class SubscribeController {

    @Value("${file.templete}")
    private String path;

    @Value("${file.path}")
    private String filePath;


    @Autowired
    private SubscribeService subscribeService;

    @Autowired
    private EmailService emailService;

    @Transactional
    @PostMapping("/save")
    public Result save(@RequestBody Subscribe subscribe) throws IOException {
//        email = URLDecoder.decode(email,"UTF-8");

        log.info("email:{}",subscribe.getEmail());
        subscribe.setUpdateTime(LocalDateTime.now());
        subscribe.setStatus(StatusEnum.ENABLE);
//        emailService.sendSimpleMail(subscribe.getEmail(),"我是你爹","这是一封测试邮件",null);

        File fileName = new File(path); // 相对路径
        BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.error("读取文件失败，fileName:{}", fileName, e);
        } finally {
            fileReader.close();
        }
        // 替换参数
        String htmlText = buffer.toString();


        Subscribe one = subscribeService.getOne(new LambdaQueryWrapper<Subscribe>()
                .eq(Subscribe::getEmail, subscribe.getEmail()));



        if (one != null){
            return new Result<>(405,"已存在该邮箱");
        }



        log.info("subscribe:{}",subscribe);

        boolean save = subscribeService.save(subscribe);
        if (save){
            emailService.sendHtmlMail(new String[]{subscribe.getEmail()}, "测试",htmlText ,null);
        }
        return save? Result.success("提交成功") : Result.error("失败");
    }

    @PreAuthorize("hasAnyAuthority('sys:delete:subscribe')")
    @Transactional
    @DeleteMapping("/{ids}")
    public Result delById(@PathVariable List<Long> ids){

        boolean b = subscribeService.removeByIds(ids);

        return b? Result.success("删除成功") : Result.error("删除失败");
    }


    @PreAuthorize("hasAnyAuthority('sys:select:subscribe')")
    @GetMapping("/get-subscribe")
    public Result getSubscribe(Integer pageNo, Integer pageSize, String email, Integer status){
        IPage iPage = new Page(pageNo,pageSize);
        iPage = subscribeService.page(iPage,new LambdaQueryWrapper<Subscribe>()
                .like(email != null,Subscribe::getEmail,email)
                .eq(status != null,Subscribe::getStatus,status)
                .orderByDesc(Subscribe::getUpdateTime));

        return Result.success("查询成功",iPage);
    }

    @PreAuthorize("hasAnyAuthority('sys:send:subscribe')")
    @PostMapping("/send-email")
    public Result sendEmail(@RequestBody Email email){
        log.info("email:{}",email);
        if (email.getEmails() == null || email.getEmails().isEmpty()){
            List<String> collect = subscribeService.list(new LambdaQueryWrapper<Subscribe>()
                            .eq(Subscribe::getStatus, 0))
                    .stream().map(Subscribe::getEmail).collect(Collectors.toList());
            email.setEmails(collect);
        }
        if (email.getFilePath() != null && !"".equals(email.getFilePath())){
            try {
                emailService.sendAttachmentsMail(email.getEmails().toArray(new String[]{}), email.getSubject(), email.getContent(), filePath + email.getFilePath(), null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                emailService.sendHtmlMail(email.getEmails().toArray(new String[]{}), "测试", email.getContent(), null);
            } catch (Exception e) {
                throw new RuntimeException(e);

            }
        }
        return Result.success("发送成功");
    }



    @PreAuthorize("hasAnyAuthority('sys:update:subscribe')")
    @Transactional
    @PutMapping("/update")
    public Result update(@RequestBody List<Subscribe> subscribe){
        boolean b = subscribeService.updateBatchById(subscribe);
        return b ? Result.success("修改成功") : Result.error("修改失败");
    }
}
